from django.dispatch        import dispatcher
from django.db.models       import signals, get_apps, get_models
from django.core.management import _get_table_list, _get_sql_model_create
from django.db              import connection
from utils                  import create_history_model
from .                      import history_model_cache, log

"""
    Does the work of installing history model tables for history enabled classes
    on syncdb.
"""


installed_tables = _get_table_list()


def install_table(model):
    """
        Installs a table for a given model. Taken from:
            http://code.djangoproject.com/wiki/DynamicModels
    """
    # Standard syncdb expects models to be in reliable locations,
    # so dynamic models need to bypass django.core.management.syncdb.
    # On the plus side, this allows individual models to be installed
    # without installing the entire project structure.
    # On the other hand, this means that things like relationships and
    # indexes will have to be handled manually.
    # This installs only the basic table definition.

    print "Installing table for %s..." % model.__name__

    cursor = connection.cursor()
    statements, pending = _get_sql_model_create(model)
    for sql in statements:
        cursor.execute(sql)



def create_history_table_for_model(model_class):
    """
        Helper function that creates a history model and installs a table for
        it.
    """

    new_history_model = create_history_model(model_class)
    install_table(new_history_model)



def install_model_history(app, *args, **kwargs):
    """
        Handles post_syncdb signals. Checks to see if models for given app are
        history-enabled. If so it checks to see if a history table has been installed:
        if not it installs the appropriate history log table.
    """
    app_models = get_models(app)
    if not app_models:
        return
    for model_class in app_models:
        try:
            if getattr(model_class, 'History'):
                opts = model_class._meta
                if model_class in history_model_cache:
                    if (opts.app_label + '_' + opts.module_name + 'history') in installed_tables:
                        continue
                create_history_table_for_model(model_class)
        except AttributeError:
            continue


dispatcher.connect(install_model_history, signal=signals.post_syncdb)
#log("management imported")
